package com.mmcg.service.impl;

import com.mmcg.service.PortalService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.RemoteCategoryService;
import com.ruoyi.system.api.domain.Content;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者：李嘉浩
 * 时间：2024-09-07-23:45
 * 功能：
 */
@Service
public class PortalServiceImpl implements PortalService {

    @Autowired
    private RemoteCategoryService remoteCategoryService;

    @Autowired
    private RedisService redisService;
    @Override
    public List<Content> findByCategoryId(long l) {

        Collection<Object> values = redisService.getCacheMap(CacheConstants.CONTENT_MAP).values();
        List<Content> contents;

        if (!CollectionUtils.isEmpty(values)){
            contents=values.stream().map(m -> (Content) m).collect(Collectors.toList());
        }else {
            R<List<Content>> byCategoryId = remoteCategoryService.findByCategoryId(l);
            contents = byCategoryId.getData();
            for (Content content : contents) {
                redisService.setCacheMapValue(CacheConstants.CONTENT_MAP,content.getId()+"",content);
            }
        }
        return contents;
    }

    @Override
    @Cacheable(cacheNames = "contentList",key = "#p0")
    public List<Content> findByCategoryId1(long l) {
        R<List<Content>> byCategoryId = remoteCategoryService.findByCategoryId(l);
        List<Content> data = byCategoryId.getData();
        return data;
    }

    @Override
    @Cacheable(cacheNames = "findById",key = "#p0")
    public Content findById(Long id) {
        R<Content> r = remoteCategoryService.findById(id);
        Content data = r.getData();
        return data;
    }
}
